home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / mint / utilit~1 / futilsrc.zoo / fileutil / lib / dirname.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-20  |  1.6 KB  |  60 lines

  1. /* dirname.c -- return all but the last element in a path
  2.    Copyright (C) 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. #ifdef STDC_HEADERS
  19. #include <stdlib.h>
  20. #else
  21. char *malloc ();
  22. #endif
  23. #if defined(USG) || defined(STDC_HEADERS)
  24. #include <string.h>
  25. #define rindex strrchr
  26. #else
  27. #include <strings.h>
  28. #endif
  29. char *strdup ();
  30.  
  31. /* Return the leading directories part of PATH,
  32.    allocated with malloc.  If out of memory, return 0.
  33.    Assumes that trailing slashes have already been
  34.    removed.  */
  35.  
  36. char *
  37. dirname (path)
  38.      char *path;
  39. {
  40.   char *newpath;
  41.   char *slash;
  42.   int length;    /* Length of result, a la strlen. */
  43.  
  44.   slash = rindex (path, '/');
  45.   if (slash == 0)
  46.     return strdup (".");
  47.  
  48.   /* Remove any trailing slashes from result. */
  49.   while (slash > path && *slash == '/')
  50.     --slash;
  51.  
  52.   length = slash - path + 1;
  53.   newpath = malloc (length + 1);
  54.   if (newpath == 0)
  55.     return 0;
  56.   strncpy (newpath, path, length);
  57.   newpath[length] = 0;
  58.   return newpath;
  59. }
  60.